import 'dart:convert';
import 'dart:io';
import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:ls_work/net/api/http_api.dart';
import 'package:ls_work/util/request_url_utils.dart';
// import 'package:visitor_scan_package/net/api.dart';

class SetUrlViewModel extends BaseViewModel{
  final String address;
  SetUrlViewModel(BuildContext context,this.address) : super(context);

  Socket? socket;

  @override
  void onCreated() {
    super.onCreated();
    connect();
  }

  void connect(){
    var list = address.split(":");
    Socket.connect(list[0], list[1].toInt()??0)
    .then((socket) {
       this.socket = socket;
       this.socket?.listen((event) {
         var str = String.fromCharCodes(event);
         if(str=="success"){
           showToast("设置成功");
           finish();
         }
       });
    }).onError((error, stackTrace){
      showToast("连接失败");
      finish();
    });
  }

  @override
  void onDispose() {

    super.onDispose();

  }

  @override
  void dispose() {
    socket?.close();
    super.dispose();
  }
  
  void sendData(){
    var map = {
      "baseUrl":HttpApi.baseUrl,
      "type":"urlSet",
      "code": RequestUrlUtils.code
    };
    socket?.write(jsonEncode(map));
  }
}